import { readFileSync, writeFileSync } from 'fs';
import { parse, stringify } from 'yaml';
import { add, commit } from 'isomorphic-git';
import * as fs from 'fs';

export default async function () {
  const pathToDeployment = 'deployment/kyc-doc';

  const currentVersion = readFileSync(`${pathToDeployment}/version`, {
    encoding: 'utf8',
  });
  console.log(`Current version is ${currentVersion}`);
  const fragments = currentVersion.split('.');
  fragments[2] = String(parseInt(fragments[2]) + 1);
  const newVersion = fragments.reduce((a, b) => `${a}.${b}`);
  console.log(`New version is ${newVersion}`);

  writeFileSync(`${pathToDeployment}/version`, newVersion);

  const valueDoc = parse(
    readFileSync(`${pathToDeployment}/chart/Chart.yaml`, { encoding: 'utf8' })
  );
  valueDoc.version = newVersion;
  writeFileSync(`${pathToDeployment}/chart/Chart.yaml`, stringify(valueDoc), {
    encoding: 'utf8',
  });

  try {
    await add({
      fs,
      dir: '',
      filepath: [
        'deployment/kyc-doc/version',
        'deployment/kyc-doc/chart/Chart.yaml',
      ],
    });
    await commit({
      fs,
      dir: '',
      message: 'chore(kyc-doc): increase doc version',
    });
  } catch (e) {
    console.error(e);
  }

  console.log('\n');
  console.log('done');
}
